package com.bawei.detail.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.common.vm.BaseViewModel
import com.bawei.detail.entity.DanmuEntity
import com.bawei.detail.intent.DetailViewIntent
import com.bawei.detail.model.DetailRepository
import com.bawei.detail.model.MovieDetailPagingSource
import com.bawei.detail.state.DetailUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/2/11
 * Desc:
 */

@HiltViewModel
class DetailViewModel @Inject constructor(private val repository: DetailRepository):BaseViewModel<DetailViewIntent>() {

    private var _uiState  = MutableStateFlow<DetailUiState>(DetailUiState.LoadEmpty)
    val uiState: StateFlow<DetailUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: DetailViewIntent) {
        when(intent){
            is DetailViewIntent.LoadAuthorInfo -> loadAuthorInfo(intent.userId)
            is DetailViewIntent.LoadMovieCommend -> loadMovieCommend(intent.dataType, intent.itemId)
            is DetailViewIntent.PublishDanmuMsg -> publishDanmuMsg(intent.entity)
            is DetailViewIntent.LoadBulletScreenInfo -> loadBulletScreenInfo(intent.dataType, intent.itemId)
        }
    }
    //20250215 游戏鸿蒙-i视频-10-性能升级-多版本兼容 获取历史弹幕
    private fun loadBulletScreenInfo(dataType: Int, itemId: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                withContext(Dispatchers.Main){
                    val (code, data, msg) = repository.getBulletScreenInfo(dataType, itemId)
                    if (code == 0) {
                        _uiState.value = DetailUiState.LoadBulletScreenInfoSuccess(data)
                    } else {
                        _uiState.value = DetailUiState.LoadBulletScreenInfoFail(msg)
                    }
                }
            } catch (e:Exception){
                withContext(Dispatchers.Main){
                    _uiState.value = DetailUiState.LoadBulletScreenInfoFail("获取评论异常")
                }
            } finally {
                cancel()
            }
        }
    }
    //20250215 游戏鸿蒙-i视频-10-性能升级-多版本兼容 发送弹幕
    private fun publishDanmuMsg(entity: DanmuEntity) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                withContext(Dispatchers.Main){
                    val (code, data, msg) = repository.publishDanmuMsg(entity)
                    if (code == 0) {
                        _uiState.value = DetailUiState.PublishDanmuMsgSuccess(data)
                    } else {
                        _uiState.value = DetailUiState.PublishDanmuMsgFail(msg)
                    }
                }
            } catch (e:Exception){
                withContext(Dispatchers.Main){
                    _uiState.value = DetailUiState.PublishDanmuMsgFail("发送评论异常")
                }
            } finally {
                cancel()
            }
        }
    }

    private fun loadAuthorInfo(userId: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val (code, data, msg) = repository.getAuthorInfoById(userId)
                if (code == 0 && data != null){
                    withContext(Dispatchers.Main){
                        _uiState.value = DetailUiState.LoadAuthorInfoSuccess(data)
                    }
                }else{
                    withContext(Dispatchers.Main){
                        _uiState.value = DetailUiState.LoadAuthorInfoFail("没有查询到作者信息")
                    }
                }

            }catch (e: Exception){
                e.printStackTrace()
                withContext(Dispatchers.Main){
                    _uiState.value = DetailUiState.LoadAuthorInfoFail("请求异常！")
                }
            }finally {
                cancel()
            }
        }
    }

    private fun loadMovieCommend(dataType: Int, itemId: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val (code, data, msg) = repository.getMovieCommendById(dataType, itemId)
                if (code == 0 && data.isNotEmpty()){
                    withContext(Dispatchers.Main){
                        _uiState.value = DetailUiState.LoadMovieCommendSuccess(data)
                    }
                }else{
                    withContext(Dispatchers.Main){
                        _uiState.value = DetailUiState.LoadMovieCommendFail("没有查询到评论信息")
                    }
                }

            }catch (e: Exception){
                e.printStackTrace()
                withContext(Dispatchers.Main){
                    _uiState.value = DetailUiState.LoadMovieCommendFail("请求异常！")
                }
            }finally {
                cancel()
            }
        }
    }

    /**
     * 获取推荐电影列表
     */
    fun loadRecommendVideo(): Flow<PagingData<MovieVideoEntity>> {
        return Pager(config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false), pagingSourceFactory = { MovieDetailPagingSource() }).flow.cachedIn(viewModelScope)
    }


    /**
     * 获取分类电影列表
     */
    fun loadMutilVideoById(typeId: Int): Flow<PagingData<MovieVideoEntity>> {
        return Pager(config = PagingConfig(initialLoadSize = 1, pageSize = 10, enablePlaceholders = false), pagingSourceFactory = { MovieDetailPagingSource(typeId)}).flow.cachedIn(viewModelScope)
    }











}